<?php

namespace addons\booking\model;

use think\Model;
use addons\booking\model\Store as StoreModel;
use addons\booking\model\OrderFirst;
use addons\booking\model\StoreBill;
use addons\booking\model\StoreOrderSon;
use addons\booking\model\StoreOrerRoom;
use addons\booking\model\House as HouseModel;
use addons\booking\model\RoomState;
use think\Db;

class StoreOrder extends Model
{

    // 表名
    protected $name = 'store_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    public static function uni_order_sn()
    {
        //日期
        $order_date = date('Y-m-d');
        //订单号主体
        $order_id_main = date('YmdHis') . rand(10000000,99999999);
        //订单号长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
        }
        //唯一订单号
        $order_sn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        return $order_sn;
    }

    //余额支付保证金
    public static function yueMarginPay(array $orderInfo, $store_id)
    {
        if (!$orderInfo) {
            return ['status' => false,'msg'=>'订单不存在!'];
        }
        if ($orderInfo['margin_paid']) {
            return ['status' => false,'msg'=>'该订单已支付!'];
        }

        $type = 'pay_product';
        if (isset($orderInfo['member_type'])) {
            $type = 'pay_member';
        }
        //判断余额是否充足
        $storeInfo = StoreModel::where('id',$store_id)->find();
        if($storeInfo['money'] < $orderInfo['pay_margin_price']){
            return ['status' => false, 'msg' => '余额不足' . floatval($orderInfo['pay_margin_price'])];
        }

        DB::startTrans();
        try{
            //更新酒店账户余额
            StoreModel::where( 'id', $store_id )->setDec( 'money', $orderInfo['pay_margin_price'] );
            //写入余额记录
            $StoreBill = new StoreBill();
            $StoreBill->income('order_margin',$store_id, $orderInfo['pay_margin_price'], $storeInfo['money'], $orderInfo['id']);
            //更新订单状态
            self::payMarginSuccess($orderInfo, 'balance');//余额支付保证金成功

            Db::commit();
            return ['status' => true,'msg'=>'支付成功'];
        }catch (\Exception $e){
            Db::rollback();
//            dump($e->getMessage());die;
            return ['status' => false,'msg'=>'支付失败'];
        }
        return ['status' => false,'msg'=>'支付失败'];
    }

    public static function payMarginSuccess(array $orderInfo, string $paytype = 'weixin', array $other = [])
    {
        if ($paytype == 'alipay' && isset($other['trade_no'])) {
            $updata['trade_no'] = $other['trade_no'];
        }
        $updata['margin_paid'] = 1;
        $updata['margin_pay_type'] = $paytype;
        $updata['pay_margin_time'] = time();
        $res = self::where('id',$orderInfo['id'])->update($updata);


        return false !== $res;
    }

    //订单列表
    public static function getList($store_id=0,$type=0,$page=1,$limit=10)
    {
        $where['a.store_id'] = $store_id;
        switch ($type) {
            case 0: //全部

                break;
            case 1: //待支付
                $where['a.status'] = "0";
                $where['a.margin_paid'] = 0;
                break;
            case 2://待接单
                $where['a.status'] = "0";
                $where['a.margin_paid'] = 1;
                break;
            case 3://进行中
                $where['a.status'] = "1";
                break;
            case 4://已完成
                $where['a.status'] = ['in',["2","3"]];
                break;
            case 5://已取消
                $where['a.status'] = "4";
                break;
        }
        $list = self::alias('a')->
                with([
                    'Son' => function ($query) {
                        $query->alias('s')->join('worker w','s.worker_id = w.id','left')
                            ->where('s.status','in',["0","1","2","3","4"])
                            ->field('s.id,s.worker_id,s.status,s.order_id,w.user_name,w.head_image,w.mobile,w.longitude,w.latitude');
                    },
                ])
                ->join('store_user b','a.store_user_id = b.id','left')
                ->where($where)
                ->field('a.id,a.order_sn,a.status,a.store_user_id,a.status,b.user_name,a.arrival_time,a.costs_total_price,a.worker_num,a.create_time')
                ->order('create_time desc')
                ->paginate($limit)->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['expire_time'] = $v['create_time'] + 60 * 60;
            $list['data'][$k]['son_num'] = StoreOrderSon::where('order_id',$v['id'])->where('status','in',['1','2','3','4'])->count();
            $list['data'][$k]['room_num'] = Db::name('order_room')->where('order_id',$v['id'])->where('status','in',['0','1','2','3','4'])->count();

        }
        return $list;
    }

    //酒店取消订单
    public static function cancel_order($order_id)
    {
        $order = self::where('id',$order_id)->find();

        $order_son = StoreOrderSon::where('order_id',$order_id)->where('status','in',['1','2','3','4','5'])->select();
        if($order_son){

        }

        DB::startTrans();
        try{
            $time = time();
            //更新订单状态
            self::where('id',$order_id)->update(['status'=>4,'cancel_time'=>$time]);
            //补贴保洁
            if($order_son){
                //写入余额记录
                $StoreBill = new StoreBill();
                //$StoreBill->income('order_margin',$store_id, $orderInfo['pay_margin_price'], $storeInfo['money'], $orderInfo['id']);
            }

            Db::commit();
            return ['status' => 1,'msg'=>'取消成功'];
        }catch (\Exception $e){
            Db::rollback();
            return ['status' => -1,'msg'=>'取消失败'];
        }
    }

    //指派房间
    public static function assign_room($order_id,$worker_id,$rooms)
    {
        $order = self::where('id',$order_id)->find();
        if($order['status'] > 1) return ['status' => -1,'msg'=>'订单状态无法指派'];
        $rooms_arr =  explode(',',$rooms);
        if(!$rooms_arr) return ['status' => -1,'msg'=>'房间参数错误'];
        $order_room = StoreOrerRoom::where('order_id',$order_id)
            ->where('room_id','in',$rooms_arr)
            ->where('status','<',5)
            ->find();
        if($order_room)  return ['status' => -1,'msg'=>'有房间无法指派'];
        $insertAll = [];
        foreach ($rooms_arr as $k=>$v){
            $map = [];
            $map['order_id'] = $order['id'];
            $map['worker_id'] = $worker_id;
            $map['room_id'] = $v;
            $map['status'] = 1;
            $map['store_id'] = $order['store_id'];
            $map['create_time'] = time();
            $house = HouseModel::where('id',$v)->find();
            $map['price'] = $house['price'];
            $insertAll[] = $map;
        }

        DB::startTrans();
        try{
            $time = time();
            //新增房间分派表
            StoreOrerRoom::insertAll($insertAll);
            //更新房态表
            $arrival_date = $order['arrival_date'];
            $where['date'] = $arrival_date;
            $where['store_id'] = $order['store_id'];
            $where['house_id'] = ['in',$rooms_arr];
            RoomState::where($where)->update(['status'=>2]);
            Db::commit();
            return ['status' => 1,'msg'=>'指派成功'];
        }catch (\Exception $e){
            Db::rollback();
            return ['status' => -1,'msg'=>'指派失败'];
        }
    }

    public function StoreUser()
    {
        return $this->belongsTo('\addons\booking\model\StoreUser', 'store_user_id', 'id');
    }

    //优先指派
    public function First()
    {
        return $this->hasMany(OrderFirst::class, 'order_id', 'id');
    }

    //酒店
    public function Store()
    {
        return $this->belongsTo('Store', 'store_id', 'id');
    }

    //接单人员
    public function Son()
    {
        return $this->hasMany('StoreOrderSon', 'order_id', 'id');
    }
}
